{% extends "admin/admin_base.html" %}

{% block title %}订单管理{% endblock %}
{% block breadcrumb %}订单管理{% endblock %}

{% block content %}
<style>/* 订单统计模块 */
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 1.25rem;
    margin-bottom: 1.5rem;
}

.stat-card {
    background-color: white;
    border-radius: 0.75rem;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    padding: 1.25rem;
    transition: transform 0.2s ease;
}

.stat-card:hover {
    transform: translateY(-3px);
}

.stat-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.75rem;
}

.stat-card-icon {
    width: 38px;
    height: 38px;
    border-radius: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
}

.stat-card-icon.total {
    background-color: var(--primary-color);
}

.stat-card-icon.paid {
    background-color: var(--success-color);
}

.stat-card-icon.unpaid {
    background-color: var(--warning-color);
}

.stat-card-icon.refunded {
    background-color: var(--danger-color);
}

/* 统计图表容器 */
.chart-container {
    background-color: white;
    border-radius: 0.75rem;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    padding: 1.25rem;
    margin-bottom: 1.5rem;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    border-bottom: 1px solid var(--light-color);
    padding-bottom: 0.75rem;
}

.chart-period {
    display: flex;
    gap: 0.5rem;
}

.period-btn {
    padding: 0.25rem 0.75rem;
    border-radius: 0.5rem;
    border: 1px solid var(--light-color);
    background-color: white;
    font-size: 0.75rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.period-btn.active {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
}

/*#orderTrendChart {*/
/*    width: 100% !important; !* 让 canvas 100% 填充 *!*/
/*    height: 100% !important;*/
/*}*/

.form-control, .form-select {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #DCDFE6;
    border-radius: 0.5rem;
    font-size: 0.875rem;
    transition: border-color 0.2s ease;
}

.form-control:focus, .form-select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
}

.filters-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
    margin-top: 1rem;
}

/* 表格样式 */
.data-table {
    background-color: white;
    border-radius: 0.75rem;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.table-header {
    padding: 1rem 1.25rem;
    border-bottom: 1px solid var(--light-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-actions {
    display: flex;
    gap: 0.75rem;
}

.btn {
    padding: 0.5rem 1rem;
    border-radius: 0.5rem;
    font-weight: 500;
    font-size: 0.875rem;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
}

.btn-primary {
    background-color: var(--primary-color);
    color: white;
}

.btn-outline {
    background-color: transparent;
    border: 1px solid var(--light-color);
    color: #4E5969;
}


table {
    width: 100%;
    min-width: 640px;
}

th, td {
    padding: 1rem 0.5rem;
    text-align: left;
}

tbody tr {
    border-bottom: 1px solid var(--light-color);
    transition: background-color 0.2s ease;
}

tbody tr:hover {
    background-color: rgba(22, 93, 255, 0.02);
}

.badge {
    padding: 0.25rem 0.5rem;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 500;
}

.badge-success {
    background-color: rgba(0, 180, 42, 0.1);
    color: var(--success-color);
}

.badge-danger {
    background-color: rgba(245, 63, 63, 0.1);
    color: var(--danger-color);
}

.badge-warning {
    background-color: rgba(255, 125, 0, 0.1);
    color: var(--warning-color);
}



.action-btn {
    background: none;
    border: none;
    color: #86909C;
    cursor: pointer;
    padding: 0.25rem;
    margin: 0 0.125rem;
    transition: color 0.2s ease;
}

.action-btn:hover {
    color: var(--primary-color);
}

.action-btn.danger:hover {
    color: var(--danger-color);
}

/*.btn-danger {*/
/*    background-color: var(--danger-color);*/
/*    color: white;*/
/*}*/

.btn-danger:hover {
    background-color: #E03030;
    color: white;
}

/* 分页样式 */
.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.25rem;
    border-top: 1px solid var(--light-color);
}

.pagination {
    display: flex;
    gap: 0.5rem;
}

.page-btn {
    width: 32px;
    height: 32px;
    border-radius: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: transparent;
    border: 1px solid var(--light-color);
    color: #4E5969;
    cursor: pointer;
    transition: all 0.2s ease;
    text-decoration: none;
}

.page-btn.active {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
}

/* 空状态提示 */
.empty-state {
    padding: 4rem 2rem;
    text-align: center;
    color: #86909C;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: #DCDFE6;
}

/* 模态框样式 */
.form-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.form-modal.show {
    opacity: 1;
    visibility: visible;
}

.modal-content {
    background-color: white;
    border-radius: 0.75rem;
    width: 100%;
    max-width: 800px;
    max-height: 90vh;
    overflow-y: auto;
    transform: translateY(-20px);
    transition: transform 0.3s ease;
}

.form-modal.show .modal-content {
    transform: translateY(0);
}

.modal-header {
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid var(--light-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-body {
    padding: 1.5rem;
}

.modal-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--light-color);
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
}

.order-details {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1.5rem;
}

.detail-section {
    margin-bottom: 1.5rem;
}

.detail-section-title {
    font-weight: 600;
    margin-bottom: 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid var(--light-color);
}

.detail-item {
    margin-bottom: 0.75rem;
}

.detail-label {
    font-size: 0.875rem;
    color: #86909C;
    margin-bottom: 0.25rem;
}

.detail-full-width {
    grid-column: 1 / -1;
}

/* 上月对比数据（浅色辅助） */
.stat-card-compare-value {
    font-size: 0.75rem;
    color: #86909C;
    margin-top: 15px;
    float: right;
    text-align: right;
}

/* 响应式样式 */
@media (max-width: 992px) {
    .sidebar {
        position: fixed;
        left: -250px;
        height: 100vh;
    }

    .sidebar.show {
        left: 0;
    }

    .order-details {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .pagination-container {
        flex-direction: column;
        gap: 1rem;
        align-items: flex-start;
    }

    .filter-groups {
        grid-template-columns: 1fr;
    }
}
</style>
<!-- 提示弹窗（用于显示保存成功/失败信息） -->
<div class="toast" id="toast"></div>
<!-- 订单管理内容 -->
<!--<h2 class="mb-4">订单管理</h2>-->

<div class="stats-container">
    <!-- 总订单数 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <span class="stat-card-title">总订单数</span>
            <div class="stat-card-icon total">
                <i class="fas fa-shopping-bag"></i>
            </div>
        </div>
        <div class="stat-card-value" id="totalOrderCount">
            {{ stats.total_orders }}
            <span class="stat-card-compare-value">
                上月: {{ monthly_stats.last_month.orders }} - 本月: {{ monthly_stats.this_month.orders }}
            </span>
        </div>
        <div class="stat-card-trend trend-{{ 'up' if monthly_stats.growth_rate.orders  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if monthly_stats.growth_rate.orders  > 0 else 'down' }}"></i>
            <span>较上月{{ '增长' if monthly_stats.growth_rate.orders  > 0 else '下降' }} {{ "%.2f"|format(monthly_stats.growth_rate.orders) }}%</span>
        </div>
    </div>

    <!-- 总金额 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <span class="stat-card-title">总金额</span>
            <div class="stat-card-icon total">
                <i class="fas fa-yen-sign"></i>
            </div>
        </div>
        <div class="stat-card-value" id="totalOrderAmount">
            ¥{{ "%.2f"|format(stats.total_amount) }}
            <span class="stat-card-compare-value">
                上月: ¥{{ "%.2f"|format(monthly_stats.last_month.paid_amount) }} - 本月: ¥{{ "%.2f"|format(monthly_stats.this_month.paid_amount) }}
            </span>
        </div>
        <div class="stat-card-trend trend-{{ 'up' if monthly_stats.growth_rate.amount  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if monthly_stats.growth_rate.amount  > 0 else 'down' }}"></i>
            <span>较上月{{ '增长' if monthly_stats.growth_rate.amount  > 0 else '下降' }} {{ "%.2f"|format(monthly_stats.growth_rate.amount) }}%</span>
        </div>
    </div>

    <!-- 已付金额 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <span class="stat-card-title">已付金额</span>
            <div class="stat-card-icon paid">
                <i class="fas fa-check-circle"></i>
            </div>
        </div>
        <div class="stat-card-value" id="paidOrderAmount">
            ¥{{ "%.2f"|format(stats.paid_amount) }}
            <span class="stat-card-compare-value">
                上月: ¥{{ "%.2f"|format(monthly_stats.last_month.paid_amount) }} - 本月: ¥{{ "%.2f"|format(monthly_stats.this_month.paid_amount) }}
            </span>
        </div>
        <div class="stat-card-trend trend-{{ 'up' if monthly_stats.growth_rate.paid  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if monthly_stats.growth_rate.paid  > 0 else 'down' }}"></i>
            <span>较上月{{ '增长' if monthly_stats.growth_rate.paid  > 0 else '下降' }} {{ "%.2f"|format(monthly_stats.growth_rate.paid) }}%</span>
        </div>
    </div>

    <!-- 未付金额 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <span class="stat-card-title">未付金额</span>
            <div class="stat-card-icon unpaid">
                <i class="fas fa-clock"></i>
            </div>
        </div>
        <div class="stat-card-value" id="unpaidOrderAmount">
            ¥{{ "%.2f"|format(stats.unpaid_amount) }}
            <span class="stat-card-compare-value">
                上月: ¥{{ "%.2f"|format(monthly_stats.last_month.unpaid_amount) }} - 本月: ¥{{ "%.2f"|format(monthly_stats.this_month.unpaid_amount) }}
            </span>
        </div>
        <div class="stat-card-trend trend-{{ 'up' if monthly_stats.growth_rate.unpaid  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if monthly_stats.growth_rate.unpaid  > 0 else 'down' }}"></i>
            <span>较上月{{ '增长' if monthly_stats.growth_rate.unpaid  > 0 else '下降' }} {{ "%.2f"|format(monthly_stats.growth_rate.unpaid) }}%</span>
        </div>
    </div>
</div>

<!-- 统计图表 -->
<div class="chart-container">
    <div class="chart-header">
        <div class="chart-title">订单金额趋势</div>
        <div class="chart-period">
            <button class="period-btn" data-period="day">今日</button>
            <button class="period-btn active" data-period="week">本周</button>
            <button class="period-btn" data-period="month">本月</button>
        </div>
    </div>
    <div style="height: 300px;">
        <canvas id="orderTrendChart"></canvas>
    </div>
</div>

<!-- 订单表格 -->
<div class="data-table mb-4">
    <div class="table-header">
        <div class="table-title">订单列表</div>
        <div class="table-actions">
            <div class="input-group" style="width: 300px;">
                <form id="searchForm" class="input-group" style="width: 300px;" method="get">
                    <input type="text" name="search" class="form-control" placeholder="搜索订单号、用户名..."
                           value="{{ search or '' }}">
                    <button class="btn btn-primary" type="submit">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>
    <div class="table-responsive">
        <table>
            <thead>
            <tr>
                <th>订单号</th>
                <th>用户</th>
                <th>会员类型</th>
                <th>金额</th>
                <th>支付方式</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>支付时间</th>
                <th>复核</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for o in orders %}
            <tr>
                <td>{{ o.order_id }}</td>
                <td>{{ o.username }}</td>
                <td>
                    {% if o.vip_type == 'month' %}
                    <span class="badge badge-month">金牌用户</span>
                    {% elif o.vip_type == 'season' %}
                    <span class="badge badge-season">铂金用户</span>
                    {% elif o.vip_type == 'year' %}
                    <span class="badge badge-year">至尊用户</span>
                    {% elif o.vip_type == 'admin' %}
                    <span class="badge badge-admin">至尊用户</span>
                    {% else %}
                    <span class="badge badge-free">普通用户</span>
                    {% endif %}
                </td>
                <td>¥{{ "%.2f"|format(o.amount) }}</td>
                <td>
                    {% if o.pay_type == 'wxpay' %}
                        <span class="badge badge-free">
                            <img src="/static/images/wxpay.png" alt="微信" style="width: 20px; margin-right: 5px;">
                            微信
                        </span>
                    {% elif o.pay_type == 'alipay' %}
                        <span class="badge badge-free">
                            <img src="/static/images/alipay.png" alt="支付宝" style="width: 20px; margin-right: 5px;">
                            支付宝
                        </span>
                    {% elif o.pay_type == 'kami' %}
                        <span class="badge badge-free">
                            <img src="/static/images/kami.png" alt="卡密" style="width: 20px; margin-right: 5px;">
                            卡密
                        </span>
                    {% else %}
                    <span class="badge badge-free">other</span>
                    {% endif %}


                </td>
                <td>
                    {% if o.status == 'paid' %}
                    <span class="badge badge-success">已支付</span>
                    {% elif o.status == 'pending' %}
                    <span class="badge badge-warning">未支付</span>
                    {% else %}
                    <span class="badge badge-danger">支付失败</span>
                    {% endif %}
                </td>
                <td>{{ o.created_at }}</td>
                <td>{{ o.paid_at or "-" }}</td>
                <td>
                    {% if o.is_verified == 1 %}
                    <span class="badge badge-success">已复核</span>
                    {% elif o.is_verified == 0 %}
                    <span class="badge badge-danger">未复核</span>
                    {% else %}
                    <span class="badge badge-warning">其它</span>
                    {% endif %}
                </td>
                <td>{{ o.remark }}</td>
                <td>
                    {% if o.status != "paid" %}
                    <button class="action-order-btn btn btn-sm btn-outline-danger manual-add-order" data-id="{{ o.order_id }}"
                            data-action="hand"  title="手动补单" style="border: 1px solid;">
                        <i class="fas fa-hand-holding-usd"></i> 补单
                    </button>
                    {% else %}
                    <button class="action-order-btn btn btn-sm btn-outline-success" title="启用" data-id="{{ o.order_id }}"
                            data-action="check"  title="订单复核" style="border: 1px solid;">
                        <i class="fas fa-check"></i> 复核
                    </button>
                    {% endif %}

                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

    <div class="pagination-container d-flex justify-content-between align-items-center mt-3">
        <div class="pagination-info">显示 {{ orders|length }} 条，共 {{ total_orders }} 条</div>
        <div class="pagination">
        <!-- 上一页 -->
        <a href="?page={{ page-1 if page > 1 else 1 }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == 1 %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-left"></i>
        </a>

        <!-- 分页按钮（修复 max/min 问题） -->
        {% if total_pages > 0 %}
            {% set start_page = (page - 2) if (page - 2) >= 1 else 1 %}
            {% set end_page = (page + 2) if (page + 2) <= total_pages else total_pages %}
            {% for p in range(start_page, end_page + 1) %}
                <a href="?page={{ p }}{% if search %}&search={{ search }}{% endif %}"
                   class="btn btn-outline-primary {% if p == page %}active{% endif %}">{{ p }}</a>
            {% endfor %}
        {% endif %}

        <!-- 下一页 -->
        <a href="?page={{ page+1 if page < total_pages else total_pages }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == total_pages %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-right"></i>
        </a>
    </div>
    </div>

</div>

<!-- 订单复核弹窗 -->
<div class="modal fade" id="checkOrderModal" tabindex="-1" aria-labelledby="checkOrderModalLabel" aria-hidden="true">
    <!-- 自定义弹窗宽度：中等屏幕以上60%宽度，小屏幕100% -->
    <div class="modal-dialog modal-dialog-centered modal-lg" style="max-width: 60%;">
        <div class="modal-content shadow-lg" style="border-radius: 8px; overflow: hidden;">
            <!-- 弹窗头部：增加底边框分隔，优化内边距 -->
            <div class="modal-header bg-light border-bottom py-3 px-4">
                <h5 class="modal-title fw-semibold text-gray-800" id="checkOrderModalLabel">
                    <i class="fas fa-check-circle text-primary me-2"></i>订单复核
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"
                        style="opacity: 0.7; transition: opacity 0.2s;">
                </button>
            </div>

            <!-- 弹窗主体：优化表单间距，统一元素样式 -->
            <div class="modal-body p-4">
                <form id="checkOrderForm" class="space-y-4">
                    <!-- 订单编号：只读字段，浅灰背景区分 -->
                    <div class="form-group">
                        <label for="order_id" class="form-label text-sm text-gray-600 fw-medium">订单编号</label>
                        <input type="text" id="order_id" name="order_id" class="form-control"
                               required
                               style="background-color: #f8f9fa; border-color: #dee2e6; cursor: not-allowed;">
                    </div>

                    <!-- 支付方式 + 支付金额：并排布局（节省空间） -->
                    <div class="row g-4">
                        <div class="col-md-6">
                            <label for="pay_type" class="form-label text-sm text-gray-600 fw-medium">支付方式</label>
                            <input type="text" id="pay_type" name="pay_type" class="form-control"
                                   disabled
                                   style="background-color: #f8f9fa; border-color: #dee2e6; cursor: not-allowed;">
                        </div>
                        <div class="col-md-6">
                            <label for="amount" class="form-label text-sm text-gray-600 fw-medium">支付金额</label>
                            <input type="text" id="amount" name="amount" class="form-control"
                                   disabled
                                   style="background-color: #f8f9fa; border-color: #dee2e6; cursor: not-allowed;">
                        </div>
                    </div>

                    <!-- 支付时间：只读字段 -->
                    <div class="form-group">
                        <label for="paid_at" class="form-label text-sm text-gray-600 fw-medium">支付时间</label>
                        <input type="text" id="paid_at" name="paid_at" class="form-control"
                               disabled
                               style="background-color: #f8f9fa; border-color: #dee2e6; cursor: not-allowed;">
                    </div>

                    <!-- 订单状态：可编辑下拉框，聚焦时高亮 -->
                    <div class="form-group">
                        <label for="status" class="form-label text-sm text-gray-600 fw-medium">订单状态 <span class="text-danger">*</span></label>
                        <select id="status" name="status" class="form-select" required
                                style="border-radius: 4px; transition: border-color 0.2s;">
                            <option value="pending">0 - 待支付</option>
                            <option value="paid">1 - 已支付</option>
                            <option value="expired">2 - 支付失败</option>
                        </select>
                    </div>

                    <!-- 订单复核：可编辑下拉框 -->
                    <div class="form-group">
                        <label for="is_verified" class="form-label text-sm text-gray-600 fw-medium">订单复核 <span class="text-danger">*</span></label>
                        <select id="is_verified" name="is_verified" class="form-select" required
                                style="border-radius: 4px; transition: border-color 0.2s;">
                            <option value="0">0 - 未审核</option>
                            <option value="1">1 - 已审核</option>
                            <option value="2">2 - 其它</option>
                        </select>
                    </div>

                    <!-- 复核备注：文本域，增加占位提示 -->
                    <div class="form-group">
                        <label for="remark" class="form-label text-sm text-gray-600 fw-medium">复核备注</label>
                        <textarea id="remark" name="remark" class="form-control" rows="3"
                                  placeholder="请输入复核备注（如异常原因、处理说明等）"
                                  style="border-radius: 4px; resize: vertical; transition: border-color 0.2s;"></textarea>
                    </div>
                </form>
            </div>

            <!-- 弹窗底部：优化按钮间距和样式 -->
            <div class="modal-footer bg-light border-top py-3 px-4 gap-3">
                <button type="button" class="btn btn-secondary btn-sm px-4" data-bs-dismiss="modal"
                        style="transition: background-color 0.2s;">
                    取消
                </button>
                <button type="button" class="btn btn-primary btn-sm px-4" id="submitCheckOrder"
                        style="transition: background-color 0.2s;">
                    <i class="fas fa-save me-1"></i> 提交复核
                </button>
            </div>
        </div>
    </div>
</div>


<!-- 可选：如果需要更统一的样式，可添加全局CSS（建议放页面头部） -->
<style>
/* 优化表单元素聚焦样式 */
.form-control:focus, .form-select:focus {
    border-color: #86b7fe;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.1);
    outline: none;
}

/* 优化按钮 hover 效果 */
.btn-primary:hover {
    background-color: #0b5ed7;
    border-color: #0a58ca;
}

.btn-secondary:hover {
    background-color: #6c757d;
    border-color: #6c757d;
}

/* 模态框动画优化（可选） */
.modal.fade .modal-dialog {
    transition: transform 0.3s ease-out;
    transform: translate(0, -10px);
}

.modal.show .modal-dialog {
    transform: translate(0, 0);
}
</style>
{% endblock %}

{% block scripts %}
<script src="/static/js/chart.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const ctx = document.getElementById("orderTrendChart").getContext("2d");
        let orderTrendChart;
        // 初始化图表
        function renderChart(labels, values) {
            if (orderTrendChart) {
                orderTrendChart.destroy();
            }
            orderTrendChart = new Chart(ctx, {
                type: "line",
                data: {
                    labels: labels,
                    datasets: [{
                        label: "订单金额",
                        data: values,
                        borderColor: "rgba(75, 192, 192, 1)",
                        backgroundColor: "rgba(75, 192, 192, 0.2)",
                        tension: 0.3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {display: false}
                    }
                }
            });
        }

        // 获取数据
        function fetchTrend(period) {
            fetch(`/admin/order_trend?period=${period}`)
                .then(res => res.json())
                .then(data => {
                    renderChart(data.labels, data.values);
                });
        }

        // 图表按钮切换
        document.querySelectorAll(".period-btn").forEach(btn => {
            btn.addEventListener("click", function () {
                document.querySelectorAll(".period-btn").forEach(b => b.classList.remove("active"));
                this.classList.add("active");
                const period = this.dataset.period;
                fetchTrend(period);
            });
        });

        // 默认加载今日
        fetchTrend("week");

        // 表格操作按钮
        const modal = new bootstrap.Modal(document.getElementById('checkOrderModal'));
        const checkForm = document.getElementById('checkOrderForm');
        document.querySelectorAll(".action-order-btn").forEach(btn => {
            btn.addEventListener("click", async () => {
                const order_id = btn.dataset.id;
                const action = btn.dataset.action;
                console.log(action);
                if (action === "hand") {
                    if (!confirm(`确定要手动确定订单 ${order_id} 吗？`)) return;
                    const res = await fetch(`/admin/order/action?action=${action}`, {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify({order_id: order_id, action: action})
                    });
                    const result = await res.json();
                    if (result.success) {
                        // alert("操作成功！");
                        showToast('成功', result.msg, 'success');
                        setTimeout(() => window.location.reload(), 2000);
                    } else {
                        showToast('错误', result.msg, 'error');
                    }
                }
                if (action === "check") {
                    const res = await fetch(`/admin/order/action?action=${action}`, {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify({order_id: order_id, action: 'get'})
                    });
                    const data = await res.json();
                    {#console.log(data);#}
                    if (data.success){
                        checkForm.order_id.value = order_id || "";
                        checkForm.pay_type.value = data.order.pay_type || "";
                        checkForm.amount.value = data.order.amount || "";
                        checkForm.paid_at.value = data.order.paid_at || "";
                        checkForm.status.value = data.order.status || "pending";
                        checkForm.is_verified.value = data.order.is_verified || 0;
                        checkForm.remark.value = data.order.remark || "";
                        // 显示模态框
                        modal.show();
                    } else {
                        showToast('错误', result.msg, 'error');
                        return alert(result.msg);
                    }
                }

            });
        });

        // 提交复核按钮
        document.getElementById('submitCheckOrder').addEventListener('click', async () => {
            try {
                const payload = {
                    order_id: checkForm.order_id.value,
                    status: checkForm.status.value,
                    is_verified: checkForm.is_verified.value,
                    remark: checkForm.remark.value
                };
                const res = await fetch("/admin/order/action?action=check", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(payload),
                    credentials: 'include'
                });
                const result = await res.json();
                if (result.success) {
                        // alert("操作成功！");
                        showToast('成功', result.msg, 'success');
                        // 关闭模态框
                        modal.hide();
                        setTimeout(() => window.location.reload(), 2000);
                    } else {
                        showToast('错误', result.msg, 'error');
                    }
            } catch (err) {
                console.error(err);
                alert("网络错误，请重试");
            }
        });

    });

    // 显示提示弹窗
    function showToast(title, msg, type) {
        const toast = document.getElementById('toast');
        toast.className = `toast ${type} show`;
        toast.innerHTML = `<strong>${title}!</strong> ${msg}`;
        // 3秒后自动隐藏
        setTimeout(() => {
            toast.className = 'toast';
        }, 3000);
    }

</script>
{% endblock %}

